const labelService = require('../services/label.service')

// 验证标签是否存在
const verifyLabelExists = async (ctx, next) => {
  // 取出所有要添加的标签
	const { labels } = ctx.request.body
	console.log('labels: ---', labels)

	// 判断添加的标签在 label 数据表中是否存在
	const newLabels = []
	for (let labelName of labels) {
		const label = { name: labelName }
		const [result] = await labelService.getLabelByName(labelName)
		// console.log('result---', result)
		if (!result) {
			// label数据表中不存在该标签
			const ret = await labelService.create(labelName)
			label.id = ret.insertId
		} else {
			label.id = result.id
		}
		newLabels.push(label)
	}

	ctx.labels = newLabels
	console.log('ctx.labels: ', ctx.labels)
	await next()
}

module.exports = {
	verifyLabelExists,
}
